﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PcArduinoControl
{
	public class Log
	{
		object mLockObject = new Object();
		List<StreamWriter> mStreams;

		internal SerialLog SerialLog { get; private set; }
		internal PacketLog PacketLog { get; private set; }

		internal Log()
		{
			mStreams = new List<StreamWriter>();
			SerialLog = new SerialLog(this);
			PacketLog = new PacketLog(this, 50);
		}

		void WriteLineInternal(string value)
		{
			lock (mLockObject)
			{
				foreach (StreamWriter stream in mStreams)
				{
					stream.WriteLine(value);
					stream.Flush();
				}
			}
		}

		public void AddStream(StreamWriter stream)
		{
			lock (mLockObject)
			{
				mStreams.Add(stream);
			}
		}

		public bool RemoveStream(StreamWriter stream)
		{
			lock (mLockObject)
			{
				return mStreams.Remove(stream);
			}
		}

		public void Open(string filePath)
		{

			AddStream(new StreamWriter(filePath));
			WriteLine("Log: Opened");
		}

		public void Close()
		{
			WriteLine("Log: Closed");
			lock (mLockObject)
			{
				if (mStreams != null)
				{

					foreach (StreamWriter stream in mStreams)
					{
						stream.Flush();
						stream.Close();
					}
					mStreams.Clear();
				}
			}
		}

		public void WriteLine(string line)
		{
			WriteLineInternal(DateTime.Now.ToString() + " - " + line);
		}

		public void WriteException(Exception exception)
		{
			WriteLine("Exception: " + exception.ToString());
			WriteCommunicationsLogs();
		}

		public void WriteFatalException(Exception exception)
		{
			WriteLine("Fatal Exception: " + exception.ToString());
			WriteCommunicationsLogs();
		}

		public void WriteCommunicationsLogs()
		{
			SerialLog.WriteToMainLog();
			PacketLog.WriteToMainLog();
		}
	}
}
